package com.website.dayouziblog.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.website.dayouziblog.exception.BaseErrorEnum;
import com.website.dayouziblog.exception.BaseException;
import com.website.dayouziblog.model.DO.UserDO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * token工具类
 */
public class TokenUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(TokenUtils.class);


    //token到期时间10小时(1000是1秒)
    private static final long EXPIRE_TIME = 10*60*60*1000;

    //密钥盐
    private static final String TOKEN_SECRET = "+=LAl#jdy6hij&in**3nk@jnj?";

    /**
     * 生成token
     * @param userDO
     * @return
     */
    public static String sign(UserDO userDO){
        String token = null;

        //过期时间 = 当前时间 + 设定时间
        Date expireAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        try {
            token = JWT.create()
                    //发行人
                    .withIssuer("dayouzi")
                    //存放数据
                    .withClaim("userAccount", userDO.getUserAccount())
                    //过期时间
                    .withExpiresAt(expireAt)
                    //密钥盐
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (IllegalArgumentException | JWTCreationException e) {
            LOGGER.error("token生成失败");
            e.printStackTrace();
        }

        return token;
    }


    public static String verify(String token){
        try {
            //创建token校验器
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("dayouzi").build();
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
//            LOGGER.info("token校验通过，userName: " + decodedJWT.getClaim("username").asString());
//            LOGGER.info("过期时间: " + decodedJWT.getExpiresAt());
            return decodedJWT.getClaim("userAccount").asString();
        } catch (IllegalArgumentException | JWTVerificationException e) {
            LOGGER.info("token校验失败，未通过拦截器");
            throw new BaseException(BaseErrorEnum.USER_INVALID);
        }
    }


}
